package com.gyms.fragment;


import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;

import com.classic.okhttp.beans.HVProductInfoBean;
import com.classic.okhttp.services.IUserService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.gyms.R;
import com.gyms.activity.CollectionActivity;
import com.gyms.activity.ProductDetailsActivity;
import com.gyms.adapter.MyCourseAdapter;
import com.gyms.base.BaseFragment;
import com.gyms.constant.Constants;
import com.gyms.manager.LocationManger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import constant.EventConstant;
import myInterface.OnItemClickLitener;
import refresh.PtrClassicFrameLayout;
import refresh.PtrDefaultHandler;
import refresh.PtrFrameLayout;
import refresh.PtrHandler;
import utils.StringUtils;
import weight.CommonEmptyView;
import weight.UiEvent;
import weight.head_foot_recyclerView.EndlessRecyclerOnScrollListener;
import weight.head_foot_recyclerView.HeaderAndFooterRecyclerViewAdapter;
import weight.head_foot_recyclerView.LoadingFooter;
import weight.head_foot_recyclerView.RecyclerViewStateUtils;

/**
 * 我收藏的课程 yjl
 */
public class MyCourseCollectFragment extends BaseFragment implements CommonEmptyView.UpdateClick{
    @BindView(R.id.bg_refresh_layout)
    RecyclerView bgRefreshLayout;
    @BindView(R.id.pf_collect)
    PtrClassicFrameLayout mPtrCourseCollect;
    @BindView(R.id.search_empty)
    CommonEmptyView searchEmpty;
    private CollectionActivity mActivity;
    private List<HVProductInfoBean> mdata = new ArrayList<>();
    private MyCourseAdapter mAdapter;
    private LocationManger mLocationManger;//定位的manger

    private static final int S_SPACE_RES=R.layout.view_space;

    //刷新 与加载更多
    private boolean isCanLoadMore=true;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_base_xrecycler;
    }

    @Override
    protected void initView() {
        createLoadingView("加载中", true);
        mActivity=(CollectionActivity)getActivity();
        searchEmpty.setUpDateClick(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        bgRefreshLayout.setLayoutManager(layoutManager);
        initAdapter();
        mLocationManger= LocationManger.getInstance(getActivity());
    }

    private void initAdapter() {
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        mAdapter = new MyCourseAdapter(mContext, mdata,dm.widthPixels,mActivity.loadingView,searchEmpty,bgRefreshLayout);
        mAdapter.setHeadRes(S_SPACE_RES);
        HeaderAndFooterRecyclerViewAdapter headerAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mAdapter);
        bgRefreshLayout.setAdapter(headerAndFooterRecyclerViewAdapter);
        bgRefreshLayout.addOnScrollListener(mOnScrollListener);
    }

    @Override
    protected void initListener() {
        //注册EventBus
        EventBus.getDefault().register(this);
        mAdapter.setOnItemClickLitener(new OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                HVProductInfoBean mProductBean=mdata.get(position);
                boolean isProductOnline=mProductBean.getOnShelf();
                if (isProductOnline) {
                    Intent intent = new Intent(mContext, ProductDetailsActivity.class);
                    intent.putExtra(Constants.FALG_INTENT_PRPDUCT_ID, mProductBean.getProductId());
                    startActivity(intent, false);
                }
            }
        });
        mPtrCourseCollect.disableWhenHorizontalMove(true);//解决和ViewPager的冲突
        mPtrCourseCollect.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                reFlash();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });

      /*  bgRefreshLayout.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                //刷新的时候将pageIndex始终为1
                reFlash();

            }

            @Override
            public void onLoadMore() {
                mPageIndex++;
                mIsRefreshOrLoadMore = 1;
                getVenueList();
            }
        });*/
    }

    @Override
    protected void processLogic() {
        mActivity.loadingView.show();
        getVenueList();
    }

    /**
     * 获取我的产品
     */
    private void getVenueList() {
        IUserService.getMyCollectionProductList(getActivity(), mPageIndex, PAGESIZE, 1, mLocationManger.longitude, mLocationManger.latitude, true, new ObjectCallback<ArrayList<HVProductInfoBean>>() {
            @Override
            public void onSuccess(ArrayList<HVProductInfoBean> response, String message) {
                mActivity.dialogDis(bgRefreshLayout,searchEmpty);
                if (mIsRefreshOrLoadMore == 1) {
                    RecyclerViewStateUtils.setFooterViewState(bgRefreshLayout, LoadingFooter.State.Normal);
                } else if (mIsRefreshOrLoadMore == 0) {
                    mPtrCourseCollect.refreshComplete();
                }
                if (null != response && response.size() != 0) {
                    if (mIsRefreshOrLoadMore == 0) {//刷新清空数据源
                        mdata.clear();
                    }
                    mAdapter.setData(response);
                } else {
                    if (mIsRefreshOrLoadMore == 0) {
                        showEmptyView(bgRefreshLayout,searchEmpty, 1);
                    } else {
                        isCanLoadMore=false;
                        doLoadMoreErro("没有更多的数据了");
                    }
                }
            }

            @Override
            public void onErrorT(int code, ArrayList<HVProductInfoBean> response, String errorMessage) {
                mActivity.dialogDis();
                showEmptyView(bgRefreshLayout,searchEmpty, code);
            }
            @Override
            public void onHttpErrorCall(int statusCode) {
                mActivity.dialogDis();
                showEmptyView(bgRefreshLayout,searchEmpty, Constants.NO_NET);
            }
        });
    }

    /**
     * 加载更多出现错误的处理
     */
    private void doLoadMoreErro(String erroStr) {
        if (mIsRefreshOrLoadMore == 1) {
            mPageIndex--;
//            bgRefreshLayout.setNoMoreData();
            RecyclerViewStateUtils.setFooterViewState(bgRefreshLayout, LoadingFooter.State.Normal);

            ToastUtil.showToast(mContext, erroStr);
        } else if (mIsRefreshOrLoadMore == 0) {
//            bgRefreshLayout.refreshComplete();
            mPtrCourseCollect.refreshComplete();
        }
    }

    @Override
    public void onUpdateClick() {
        mActivity.loadingView.show();
        //刷新的时候将pageIndex始终为1
        reFlash();
    }

    private void reFlash() {
        mPageIndex = 1;
        isCanLoadMore=true;
        mIsRefreshOrLoadMore = 0;
        getVenueList();
    }

    private void doLoadMore(){
        mPageIndex++;
        mIsRefreshOrLoadMore = 1;
        getVenueList();
    }

    /**
     * EventBus 接收事件
     *
     * @param uiEvent m
     */
    @Subscribe
    public void getName(UiEvent uiEvent) {
        if (uiEvent.getKey().equals(EventConstant.FLAG_REFRESH_MY_COURSE)) {
            reFlash();
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);//销毁的时候注销EventBus
    }

    /**
     * 上拉加载监听
     */

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            if(StringUtils.isNull(bgRefreshLayout)){
                return;
            }
            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(bgRefreshLayout);
            if(state == LoadingFooter.State.Loading) {
                Log.d("@Cundong", "the state is Loading, just wait..");
                return;
            }

            if (isCanLoadMore) {
                // loading more
                RecyclerViewStateUtils.setFooterViewState(getActivity(), bgRefreshLayout, PAGESIZE, LoadingFooter.State.Loading, null);
                doLoadMore();
            } else {
                //the end
                RecyclerViewStateUtils.setFooterViewState(getActivity(), bgRefreshLayout, PAGESIZE, LoadingFooter.State.TheEnd, null);
            }
        }
    };
}
